package base.utils;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import android.os.Environment;
import android.util.Log;

public class Logger {

	private static boolean mSwitch = true;

	public static void info(String tag, String info) {
		if (mSwitch) {
			Log.i(tag, info);
		}
	}

	public static void verbose(String tag, String info) {
		if (mSwitch) {
			Log.v(tag, info);
		}
	}

	public static void warn(String tag, String info) {
		if (mSwitch) {
			Log.w(tag, info);
		}
	}

	public static void error(String tag, String info) {
		if (mSwitch) {
			Log.e(tag, info);
		}
	}

	public static void debug(String tag, String info) {
		if (mSwitch) {
			Log.d(tag, info);
		}
	}

	public static boolean isLoggingEnabled() {
		// TODO Auto-generated method stub
		return mSwitch;
	}

	private static boolean _fileLogEnabled = false;
	private static PrintWriter _writer;
	private static String _logDir = Environment.getExternalStorageDirectory().getPath() + "/Schmooze/logs/";
	private static String _logFile = "/error.log";
	private static boolean _logReadFileLock = false;

	private static boolean mFileLogging = false;

	// This must be called only when the application is created.
	private static void open() {
		if (_writer != null)
			return;

		if (_fileLogEnabled && android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)) {
			File file = new File(_logDir);
			if (!file.exists()) {
				file.mkdirs();
			}
			mFileLogging = file.exists();
			if (mFileLogging) {
				try {
					_writer = new PrintWriter(new BufferedWriter(new FileWriter(_logDir + _logFile, true)));
				} catch (Throwable t) {
					t.printStackTrace();
				}
			}

		} else {
			mFileLogging = false;
		}

	}

	public static String getLogFileContent() {
		File file = new File(_logDir + _logFile);
		if (file == null || !file.exists())
			return null;

		_logReadFileLock = true;

		FileReader reader = null;
		BufferedReader buff = null;
		try {
			reader = new FileReader(file);
			buff = new BufferedReader(reader);
			StringBuffer content = new StringBuffer();
			String temp = null;
			while ((temp = buff.readLine()) != null) {
				content.append(temp.replace('\t', ' '));
				content.append('\n');
			}

			if (content.length() > 0) {
				return URLEncoder.encode(content.toString(), "UTF-8");
			}

		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			_logReadFileLock = false;
		} finally {
			_logReadFileLock = false;
			if (reader != null)
				try {
					reader.close();
				} catch (IOException e) {
				}
			if (buff != null)
				try {
					buff.close();
				} catch (IOException e) {
				}
			file.delete();
		}
		return null;
	}

	public static void writeLogToFile(String tag, String message) {
		error(tag, message);
		if (_logReadFileLock)
			return;
		open();
		if (_writer != null) {
			try {
				SimpleDateFormat timeStampFormat = new SimpleDateFormat("yyyy-MM-dd-hh.mm.ss", Locale.getDefault());
				_writer.print(timeStampFormat.format(new Date()));
				_writer.println(SystemUtils.getDevInfoBrief().toString());
				_writer.print(" T: " + tag);
				_writer.println(" M: " + message);
				_writer.flush();
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				if (_writer != null) {
					_writer.close();
					_writer = null;
				}
			}
		}
	}

	public static void writeLogToFile(String tag, String message, Throwable tr) {
		Log.e(tag, message, tr);
		if (_logReadFileLock)
			return;
		open();
		if (_writer != null) {
			try {
				SimpleDateFormat timeStampFormat = new SimpleDateFormat("yyyy-MM-dd-hh.mm.ss", Locale.getDefault());
				_writer.println(timeStampFormat.format(new Date()));
				_writer.println(SystemUtils.getDevInfoBrief().toString());
				_writer.print(" T: " + tag);
				_writer.println(" M: " + message);
				StackTraceElement[] sts = tr.getStackTrace();
				if (sts != null && sts.length > 0)
					for (StackTraceElement st : sts) {
						_writer.print(st.getClassName());
						_writer.print('.');
						_writer.print(st.getFileName());
						_writer.print('.');
						_writer.print(st.getMethodName());
						_writer.print('@');
						_writer.println(st.getLineNumber());
					}
				tr.printStackTrace(_writer);
				_writer.flush();
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				if (_writer != null) {
					_writer.close();
					_writer = null;
				}
			}
		}
	}

}
